package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wmz
 * @date 2024/1/28 16:49
 * @description OrderServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private WebSocketServer webSocketServerk;
    private Orders orders;
    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理异常结果信息（购物车为空，地址簿为空）
        Long userId = BaseContext.getCurrentId();
        //1.1购物车为空情况
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList == null || shoppingCartList.size() == 0) {
            //抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.2地址簿为空情况
        // TODO 有可能出现地址和用户对不上的情况
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //详细地址
        String address = addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(address);
        //2.向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()) + userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(address);
        orderMapper.insert(orders);
        this.orders = orders;
        //3.向订单明细表插入n条数据（根据购物车的商品决定）
        List<OrderDetail> orderDetailList = new ArrayList<>();
        OrderDetail orderDetail = null;
        for(ShoppingCart cart:shoppingCartList) {
            orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //4.清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //5.封装OrderSubmitVO数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);


        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Orders orders = new Orders();
        orders.setId(this.orders.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);//订单状态，待接单
        orders.setPayStatus(Orders.PAID);//支付状态，已支付
        orders.setCheckoutTime(LocalDateTime.now());//更新支付时间
        orderMapper.update(orders);

        //来单提醒
        //生成给客户端相应信息
        Map map = new HashMap();
        map.put("type",1);//通知类型: 1来单提醒，2客户催单
        map.put("orderId",this.orders.getId());
        map.put("content","订单号：" + ordersPaymentDTO.getOrderNumber());
        webSocketServerk.sendToAllClient(JSON.toJSONString(map));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 实现分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        //部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(ordersPage);
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 获取各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO queryStatistics() {
        //根据状态，分别查询出待接单、待派送、派送中的订单数量
        //将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(orderMapper.getCountByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.getCountByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS));

        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO queryDetail(Long id) {
        //查询订单
        Orders orders = orderMapper.getById(id);
        //查询订单详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //封装vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO,orders);
        //修改订单状态为3
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //查询订单状态
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        //拒单条件：1.订单存在，2.订单处于"待接单“状态
        if(orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //如果拒单时，用户完成付款，则需要退款；
        //由于我们没有做支付情况，此处就简单输出退款情况：
        Integer payStatus = orders.getPayStatus();
        if(payStatus == Orders.PAID) {
           /* //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);*/
            log.info("进行退款……");
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders order = new Orders();
        order.setId(ordersRejectionDTO.getId());
        order.setStatus(Orders.CANCELLED);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        //更新订单信息
        orderMapper.update(order);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //查询订单
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        //取消订单条件：1.订单存在 2.不是已完成的单子
        if(order == null || order.getStatus().equals(Orders.COMPLETED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //退款
        Integer payStatus = order.getPayStatus();
        if(payStatus == Orders.PAID){
            log.info("退款中……");
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        //更新订单
        orderMapper.update(orders);
    }
    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //查询订单
        Orders order = orderMapper.getById(id);
        //派送订单条件：1.订单存在  2.订单状态为已接单
        if(order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 管理端派送订单，根据订单id更新订单状态、派送时间
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //更新订单
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //查询订单
        Orders order = orderMapper.getById(id);
        //完成订单条件：1.订单存在  2.订单状态为派送中
        if(order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新订单状态,状态转为完成
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        //更新订单
        orderMapper.update(orders);
    }

    /**
     * c端-历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult userPageQuery(int page, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //分页查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        //将orders对象转换成orderVO
        //创建orderVOList列表，存储用户全部订单菜品详细信息
        List<OrderVO> orderVOList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(ordersPage)) {
            OrderVO orderVO = null;
            for(Orders orders:ordersPage) {
                //用户当前订单的详细信息
                orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                //查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
                //设置菜品详细信息
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);
            }
        }


        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * c端-取消订单
     * @param id
     */
    @Override
    public void userCancel(Long id) {
        //查询订单
        Orders orders = orderMapper.getById(id);

        //取消订单条件：1.订单存在 2.订单状态不大于2（待接单）
        if(orders == null || orders.getStatus() > Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //取消时，订单状态为2，需要退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            log.info("进行用户退款……");
            //设置支付状态为已退款
            orders.setPayStatus(Orders.REFUND);
        }

        //// 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户原因取消订单");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * c端-再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        if(!CollectionUtils.isEmpty(orderDetailList)) {
            // 将订单详情对象转换为购物车对象
            List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
                ShoppingCart shoppingCart = new ShoppingCart();
                // 将原订单详情里面的菜品信息重新复制到购物车对象中,除了id之外
                BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
                shoppingCart.setUserId(BaseContext.getCurrentId());
                shoppingCart.setCreateTime(LocalDateTime.now());
                return shoppingCart;
            }).collect(Collectors.toList());
            // 将购物车对象批量添加到数据库
            shoppingCartMapper.insertBatch(shoppingCartList);
        }
    }

    /**
     * c端-客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());
        //通过webSocket向客户端浏览器推送数据
        webSocketServerk.sendToAllClient(JSON.toJSONString(map));
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        String shopAddress = "北京市海淀区上地十街10号";
        String ak = "s8mtfDCaLSKsxZy3TcLULaDK2dcjTR5Q";
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 50000000){
            //配送距离超过50000000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
    /**
     * 转换显示形式：orderVO，为了订单菜品
     * @param ordersPage
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> ordersPage) {
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = ordersPage.getResult();
        if(!CollectionUtils.isEmpty(ordersList)){
            OrderVO orderVO = null;
            String orderDishes = null;
            for(Orders orders:ordersList){
                //将共同字段赋值给orderVO
                orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                //返回菜品字符串拼接
                orderDishes =  getOrderDishesStr(orders);

                //将订单菜品信息封装到orderVO中，并添加到orderVOList；
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 拼接字符串：订单详细信息中的所有商品
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        //获取订单的详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        //将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；无名子3*1；无名子3套餐包括：香辣牛杂*1，东坡肘子*1；）
        List<String> orderDishList = orderDetailList.stream().map(orderDetail -> {
           String orderDishStr = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
           if(orderDetail.getSetmealId() != null) {
               String dishStr = getSetmealDishesStr(orderDetail);
               dishStr = dishStr.substring(0,dishStr.length()-1);
               orderDishStr += orderDishStr.substring(0,orderDishStr.indexOf("*")) + "套餐包括：" + dishStr + ";";
           }
           return orderDishStr;
        }).collect(Collectors.toList());

        return String.join("",orderDishList);
    }

    /**
     * 拼接字符串：套餐包含的菜品
     * @param orderDetail
     * @return
     */
    private String getSetmealDishesStr(OrderDetail orderDetail) {
        List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishBySetmealId(orderDetail.getSetmealId());
        //如果菜品是套餐，则查询套餐包含的菜品（香辣牛杂*1，东坡肘子*1）
        List<String> dishesStr = setmealDishList.stream().map(setmealDish -> {
            String dishStr = setmealDish.getName() + "*" + setmealDish.getCopies() + ",";
            return dishStr;
        }).collect(Collectors.toList());
        return String.join("",dishesStr);
    }
}
